package com.luke.springcloud.controller;

import com.luke.springcloud.config.PersonConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Descrtption ConsulController
 * @Author luke
 * @Date 2020/4/24
 **/
@RestController
@RequestMapping("/consul")
@Slf4j
@RefreshScope //动态刷新
public class ConsulController {

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/sayHello/{name}")
    public String sayHello(@PathVariable("name") String name){
      log.info("sayHello,name:{}",name);
      return "Hi," + name;
    }

    /**
     * 获取注册中心上所有的注册实例
     * @return
     */
    @GetMapping("/getInstanceList")
    public List<ServiceInstance> getInstanceList (){
        List<ServiceInstance> instanceList = new ArrayList<>();
        discoveryClient.getServices().forEach( serviceId -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
            instanceList.addAll(instances);
        });
        return instanceList;
    }


    //--------------------------------配置中心-----------------------------------------------

    @Value("${config.name}")
    private String configName;

    @GetMapping("/getConfigName")
    public String getConfigName(){
        return configName;
    }

    @Autowired
    private PersonConfig personConfig;

    @GetMapping("/getPersonConfig")
    public PersonConfig getPersonConfig(){
        return personConfig;
    }

}
